import {mapMutations, mapState} from "vuex";
import DialogView from "@/layouts/DialogView";
import {getComponent, getMenuByKey, getParentNode} from "@/utils/routerUtil";
import {Util} from "@lowcode/jpaas-common-lib";
import qianKunAction from '@/layouts/miniFront/qianKunAction'
/**
 * 导航菜单扩展。
 */
export default {
    computed: {
        ...mapState({
            menus: state => state.appSetting.menus,
            menuStyle: state => state.appSetting.menuStyle,
            menuMap: state => state.appSetting.menuMap,
            openKeys: state => state.appSetting.openKeys,
            navigation: state => state.appSetting.navigation,
            frontType: state => state.appSetting.frontType,
            activeKey: state => state.appSetting.activeKey[state.appSetting.frontType],
        }),
        /**
         * 获取当前导航数组。
         * @returns
         */
        navTabs(){
            return this.navigation[this.frontType];
        },

    },
    methods: {
        ...mapMutations('appSetting', ['setMenuPath', "setSelecteKeys", 'setOpenKeys', 'setNavigation',
            'setActiveKey', 'sebreadlist', 'setidKey',  'setAppMenuId','setOpenFront',
            'setOpenFrontLoading','setActiveFront','setCollapsed'
        ]),
        handUrlClick(url){
            if(url) {
                var self_=this;
                var urlAry=url.split("\/");
                var flag=false;
                for (var i = 0; i < this.menus.length; i++) {
                    if(this.menus[i].key==urlAry[1]){
                        this.menu=this.menus[i];
                        this.getItemByUrl(this.menus[i].children,urlAry,3,function(item){
                            flag=true;
                            self_.$bus.emit('handUrlClick', self_.menu);
                            var path=item.path;
                            if(path){
                                var pathAry=path.split("\/");
                                for(var i=0;i<pathAry.length-1;i++){
                                    self_.openKeys.push(pathAry[i]);
                                }
                            }
                            self_.handMenuClick(item);
                        })
                    }
                }
                if(!flag){
                    let obj = {
                        title:{
                            'zh-CN':'我的待办',
                            'en-US':'My to-do list',
                        },
                        key:'MyBpmTaskList',
                        showType:'URL',
                        collapsed:true,
                    }
                    this.setActiveKey(obj.key)
                    let isIndex = this.navTabs.findIndex(nav=>{return nav.key == obj.key})
                    if(isIndex<0){
                        this.navigation[this.frontType].push(obj);
                    }
                    //静态路由跳转
                    this.$router.push({
                        path: url
                    });
                }
            }
        },
        getItemByUrl(menus,urlAry,index,callback){
            for(var i=0;i<menus.length;i++){
                if(menus[i].key==urlAry[index]){
                    if(urlAry.length==index+1){
                        if(callback){
                            callback(menus[i]);
                        }
                    }else{
                        if(menus[i].children){
                            this.getItemByUrl(menus[i].children,urlAry,index+1,callback);
                        }
                    }
                }
            }
        },
        handOpenPortal(item){//打开内置微前端
            //配置左边菜单选择key
            this.setSelecteKeys([item.key]);

            let isIndex = this.navTabs.findIndex(obj=>{ return obj.key == item.key})
            if( isIndex < 0 ){
                let menuAry = [...this.navTabs,item];
                //配置选择的 tab 数组 ；
                this.navigation[this.frontType]=menuAry;
            }
            //配置tab选中key
            this.setActiveKey(item.key);
            //给微前端传入数据；
            let state = {data:item}
            qianKunAction.setGlobalState(state);
        },
        handMenuClick(item) {
            if(item.showType == 'NEW_PAGE'){//新窗口（固定路由）
                this.openNewPage(item);
                return ;
            }
            if(['2'].includes(item.menuNavType)){//打开内置微前端
                this.handOpenPortal(item);
                return ;
            }
            //清除选中的微前端;
            this.setActiveFront({})
            this.setOpenFront(false);
            this.setOpenFrontLoading(false);

            var showType = item.showType;
            //组件路径为空 默认为目录
            if (showType == 'URL' && item.settingType == 'custom' && !item.component) {
                return;
            }

            if (showType != 'POP_WIN' && showType != 'NEW_WIN') {
                //添加tab導航
                this.handNavBars(item);

            }
            if (!showType) {
                //URL访问
                this.openUrl(item);
            }

            let _objFun = {
                "URL": {fn: 'openUrl'},  //URL访问
                "POP_WIN": {fn: 'openPopWin'},   //弹窗
                "NEW_WIN": {fn: 'openNewWin'},        //新窗口
                "FUNS": {fn: 'openFuns', parames: 'funs'},    //功能面板集（标签）
                "FUNS_BLOCK": {fn: 'openFuns', parames: 'funsBlock'},   //功能面板集（单页）
                "FUN": {fn: 'openFuns', parames: 'fun'}   //功能面板
            }
            let _fn = _objFun[showType].fn;
            let _parames = _objFun[showType].parames;
            this[_fn](item, _parames);
            this.$emit('setOpen',item);
            this.$emit('leftMenuClick', item.id)
        },
        openNewPage(item){//打开新窗口（固定路由）
            let _params = '';
            if(item.params){
                _params = item.params.indexOf('{') > -1 ? eval( '('+ item.params +')') : '' ;
            }
            let obj=this.$router.resolve({
                name:item.key,
                query:_params
            });
            let url=obj.href;
            window.open(url,"_blank" );
        },

        /**
         * 处理导航代码。
         * @param item
         */
        handNavBars(item) {

            this.setActiveKey(item.key);
            this.setSelecteKeys([item.key]);
            let _index =  this.navTabs.findIndex(nav=>{return nav.key === item.key})
            let obj = []
            if(_index > -1){
                let navObj = _.cloneDeep(this.navTabs);
                navObj.splice(_index,1,item);
                obj = navObj ;
            }else {
                obj = [...this.navTabs,item];
            }

            this.navigation[this.frontType]=obj;

        },

        openFuns(item, name) {
            var menuId = item.id;
            var pathParams = {name: name};
            if(item.appType=='1'){
                pathParams.query={appId:item.appId};
            }
            this.setSelecteKeys([item.key]);
            this.setAppMenuId(menuId)
            this.generatePath(menuId);
            pathParams.params = {}
            if (item.params) {
                pathParams.params = JSON.parse(item.params);
            }
            pathParams.params.menuId = menuId;

            this.$router.push(pathParams);
        },
        /**
         * 构造跳转参数
         * {
         *     name:"菜单KEY",
         *     params:"菜单参数",
         *     query:{
         *         appId:""
         *     }
         * }
         * @param menu
         * @returns {{name}}
         */
        handMenuPath(menu) {
            var pathParams = {name: menu.key};
            let params=menu.params;
            //用户开发的应用
            if(menu.appType=='1'){
                pathParams.query={appId:menu.appId};
            }
            //处理菜单参数
            if (params) {
                if(params.indexOf("{")!=-1 || params.indexOf("[")!=-1){
                    pathParams.params =JSON.parse(params);
                }
            }
            return pathParams;
        },
        //在弹窗中打开菜单
        openPopWin(item) {
            var data = {};
            if (item.settingType == 'iframe') {
                data.url = item.params;
            } else {
                data.menu = item;
                data.currentView = getComponent(item);
            }
            var conf = {
                component: DialogView,
                curVm: this,
                max: true,
                title: this.$i18(item.title),
                data: data
            };
            Util.open(conf);
        },
        //在新窗口打开菜单
        openNewWin(item) {
            //大屏新窗口
            if(item.settingType=="screen"){
                let params=JSON.parse(item.params);
                let url=location.protocol +"//" + location.host+params.url+"/preview/"+params.alias
                window.open(url, '_blank');
                return;
            }
            var path = process.env.VUE_APP_ADMIN_FRONT;
            var aryMenuPath = this.getMenuPath(item.id);
            var url = path;
            for (var i = 0; i < aryMenuPath.length; i++) {
                url += "/" + aryMenuPath[i].menuKey;
                if (i == 0) {
                    url += "/home";
                }
            }
            url=location.protocol +"//" + location.host +url.replace("//","/");
            //如果菜单参数为外网地址，则直接取该地址  2022-1-25
            let params=item.params;
            if(params){
                if(params.startWith('http://') || params.startWith('https://')){
                    url=params;
                }
            }
            if(item.appId){
                if(url.indexOf("?")==-1){
                    url+="?appId="+item.appId
                }else {
                    url+="&appId="+item.appId
                }
            }

            window.open(url, '_blank');
        },
        openUrl(item) {
            var key = item.key;
            var menuId = item.id;
            this.setSelecteKeys([key]);
            var path = this.handMenuPath(item);
            this.setAppMenuId(menuId);

            this.generatePath(menuId);
            /**
             *  {
             *     name:"路由名称",
             *    params: {"formAlias":"custom001",query:{name1:value1}}
             *  }
             */
            this.$router.push(path);

        },
        /**
         * 根据将菜单路径发布到VUEX
         * @param id
         */
        generatePath(id) {
            var aryMenuPath = this.getMenuPath(id);
            //将菜单路径发布到VUEX
            this.setMenuPath(aryMenuPath)
        },
        /**
         * 根据菜单ID，往上找父级菜单，放到一个数组中，直到父ID为0就停止查找。
         * @param id
         * @returns {*[]}
         */
        getMenuPath(id) {
            var aryMenuPath = [];
            var obj = this.menuMap[id];
            aryMenuPath.push(obj)
            while (obj.parentId != '0') {
                obj = this.menuMap[obj.parentId];
                //往数组开头增加元素。
                aryMenuPath.unshift(obj);
            }
            return aryMenuPath;
        },
    },
    watch:{
        /**
         * 当选中的菜单变化时，模拟点击菜单动作。
         * @param key
         */
        "frontType":function (val){

            //console.info("this.activeKey",this.activeKey);
            if(["home-index","admin-index"].contains( this.activeKey)){
                let params={name:this.activeKey};
                this.$router.push(params);
                return;
            }

            let navType=val=="user"?0:1;
            let apps=this.menus.filter(item=>{
                if(item.navType ==navType){
                    return item;
                }
            });
            let menu=getMenuByKey(this.activeKey,apps);
            if(!menu){
                return;
            }
            this.handMenuClick(menu);
        }
    }
}